from flask import Blueprint, jsonify, request,redirect
from werkzeug.security import check_password_hash,generate_password_hash
from utils.comm import get_data
from flask_mail import Mail,Message#163发邮件
from flask import current_app as app#app导包
from db import db1
import re

bp_yh = Blueprint("yh", __name__)


def send_mail(tiele,email,comment):
    mail = Mail(app)
    msg = Message(tiele,sender='qq3367812084@163.com',recipients=[email])
    msg.html = comment
    mail.send(msg)

@bp_yh.route('/zhuce', methods=['POST'])
def zhuce():
    if request.method == 'POST':
        data = get_data()
        textemail = re.match('^[a-zA-z0-9]{4,20}@163\.com$', data['email'])
        # try:
        if textemail :
            sql1 = """select * from users where email='%s'"""%data['email']
            res = db1.find_one(sql1)
            if res:
                return jsonify({"code":1001,"mes":"用户已存在"})
            else:
                sql = """insert into users values(0,'%s','%s',%d,'%s',%d)"""%(data['name'],generate_password_hash(data['password']),0,data['email'],0)
                db1.insert(sql)
                send_mail('欢迎使用163邮箱',data['email'],"欢迎使用，点击以下<a href='http://localhost:5000/yh/validEmail?email="+data['email']+"'>链接</a>验证")
                return jsonify({"code": 200})
        # except:
        #     return jsonify({"code": 10010,"mes":'服务走丢了'})

@bp_yh.route('/validEmail')
def validEmail():
    #获取email
    email = request.args.get('email')
    #更新用户表

    sql = "update users set stalt=1 where email='%s'"%(email)

    db1.insert(sql)
    return redirect('http://localhost:8888')


@bp_yh.route('/catesM')
def catesM():
    sql = """select name from cates """
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})

import math
@bp_yh.route('/shangp')
def shangp():
    cpage = int(request.args.get('cpage'))
    page_saze = 2
    start = (cpage-1)*page_saze
    sql = """select * from courses limit %d,%d"""%(start,page_saze)
    res = db1.find_all(sql)
    sql1="""select count(*) as count from courses"""
    ress =db1.find_one(sql1)
    count = math.ceil(int(ress['count'])/page_saze)
    return jsonify({"code":200,"list":res,"count":count})


@bp_yh.route('/ceshi',methods=['GET','POST'])
def ceshi():
    if request.method == 'GET':
        where = ' where 1 = 1'
        id = request.args.get('id')
        if id:
            where = where + ' and id =' + str(id)
        name = request.args.get('name')
        if name:
            where = where + ' and name = '+"'"+name +"'"
        sql = """select * from cates """+where
        # print(sql)
        res = db1.find_one(sql)
        return jsonify({"code":200,"list":res})

@bp_yh.route('/activeM',methods=['POST','GET'])
def activeM():
    if request.method == 'GET':
        sql = """select * from active"""
        res= db1.find_all(sql)
        return jsonify({"code":200,"list":res})
import time
from utils.comm import get_ali_object


@bp_yh.route('/pay')
def pay():
    alipay = get_ali_object()

    # 生成支付的url
    query_params = alipay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no="myorder" + str(time.time()),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=9999,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return redirect(pay_url)


@bp_yh.route('/canyuM',methods=['GET','POST'])
def canyuM():
    if request.method=='POST':
        data = get_data()
        email = data['email']
        cid = int(data['cid'])
        sql1 = """select * from users where email = '%s'"""%email
        res = db1.find_one(sql1)
        if res:
            vip = int(res['level'])
            if vip == 1:
                findsql = """select * from active_record where mobile = '%s' and active_id = %d"""%(email,cid)
                res = db1.find_one(findsql)
                if res:
                    return jsonify({'code': 103, 'mes': '您已经参与过了不能再参与了'})
                else:
                    vipsql = """insert into active_record(mobile,active_id,type,pay_status,money,transaction) values ('%s',%d,%d,%d,%d,%d)"""%(email,cid,1,1,0,0)
                    db1.insert(vipsql)
                    sql3 = """update active set use_count=use_count-1 where id = %d"""%cid
                    db1.insert(sql3)
                    return jsonify({'code':200,'mes':'参与成功'})
            else:
                return jsonify({'code': 104,'mes':'你没有权限参与'})
        else:
            sql4 = """select price from active where id = %d"""%cid
            res = db1.find_one(sql4)
            money = int(res['price'])
            alipay = get_ali_object()
            ddh = str(cid) + str(time.time())
            query_params = alipay.direct_pay(
                subject="和牛逼的商品",  # 商品简单描述
                out_trade_no=ddh,  # 用户购买的商品订单号（每次不一样） 20180301073422891
                total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
            )
            pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）

            btsql  = """insert into active_record(mobile,active_id,type,pay_status,money,transaction) values ('%s',%d,%d,%d,%d,'%s')"""%(email,cid,2,2,int(res['price']),ddh)
            db1.insert(btsql)
            return redirect(pay_url)


@bp_yh.route('/xiugai')
def xiugai():
        sql = """update active_record set pay_status = 1"""
        db1.insert(sql)
        return jsonify({'code':200})


